<template>
	<view class="login-page">
		<image src="../../static/image/user/loginBg.jpg" mode="widthFix" style="width: 750rpx" />

		<view class="login-box">
			<view class="flex-vc line-box">
				<i class="iconfont icon-a-shoujihaoshouji1"></i>
				<u-input class="ml15" v-model="userName" type="text" :border="false" placeholder="请输入账号" />
			</view>

			<view class="flex-vc line-box mt20">
				<i class="iconfont icon-a-mima1"></i>
				<u-input class="ml15" v-model="password" type="password" :border="false" placeholder="请输入密码" />
			</view>

			<view class="flex-vc line-box mt20">
				<i class="iconfont icon-a-zhanghuanquan1 ml5"></i>
				<u-input class="ml15" v-model="imgCode" :border="false" placeholder="请输入验证码" />

				<img :src="loginImg" mode="widthFix" v-if="loginImg" @click="getLoginImg" />
				<view v-else class="reload-btn" @click="getLoginImg">刷新</view>
			</view>

			<view class="flex-ec mt20">
				<!-- <text style="color: blue">忘记密码？</text> -->
			</view>
			<view class="flex-cc mt20">
				<view class="login-btn flex-cc" @click="submit">登录</view>
			</view>
			<u-icon name="setting-fill" color="#666" :size="40" class="posSet" @click="show = true"></u-icon>
			<u-toast ref="uToast" />

			<view class="checkboxMima">
				<u-checkbox @change="checkboxChange" v-model="isReMima"> 记住密码</u-checkbox>
			</view>
		</view>

		<u-action-sheet :list="list" v-model="show" :cancel-btn="true" @click="actionClcik"> </u-action-sheet>
	</view>
</template>
<script>
	import loginApi from '@/api/user/auth.js'
	import indexApi from '@/api/index.js'
	import Vue from 'vue'
	import { SM4Util } from './sm4.js'
	import moment from 'moment'
	import userMagApi from '@/api/user/userMag'
	let userList = {
		0: {
			userName: '',
			password: ''
		},
		1: {
			userName: '',
			password: ''
		},
		2: {
			password: ''
		},
		4: {
			userName: '',
			password: ''
		},
		3: {
			userName: '',
			password: ''
		}
	}
	let permmsion = process.env.NODE_ENV == 'development' ? 1 : 3
	export default {
		name: 'login',
		components: {},
		data() {
			return {
				appHeight: 0,
				userName: userList[permmsion].userName,
				password: userList[permmsion].password,
				imgCode: '',
				toUrl: '/pages/index/tabbar',
				codeKey: {
					code: 'xgqu',
					realKey: 'bac87c8a2e65f9301bb0a8b3debba393'
				},
				loginImg: '',
				show: false,
				list: [
					{
						text: '更新页面'
					},
					{
						text: '清除缓存'
					}
				],
				isReMima: false
			}
		},
		computed: {},
		async onLoad(options) {
			if (options && options.data) {
				this.toUrl = options.data
			}
			// 默认取图例
			this.$store.dispatch('getLegends')
			// 默认取泉州县市
			this.$store.dispatch('getCounty')

			let resp = await this.$getLocation()
			uni.setStorageSync('latlon', resp)
			// this.getLoginImg()
		},
		async mounted() {
			// this.getVersionEv()
			this.appHeight = await this.$getHeight()
			this.getLoginImg()
			Vue.prototype.$getAndSetSystemUserInfo = this.getAndSetSystemUserInfo

			this.isReMima = this.$getItem('isReMima') || false

			if (this.isReMima) {
				let data = this.$getItem('rePass')
				this.userName = (data && data.userName) || ''
				this.password = (data && data.password) || ''
			}
			// const sm4 = new SM4Util()
			// let p = sm4.encryptCustom_CBC('assadka252', '0bcefb5f5e7b26c2', 'b898a41422ab319c')
			// console.info(`p:`, p)
			// let xx = sm4.encryptCustom_CBC('123456', 'asdfghjklmnbvcx,', 'mnbvcxzpoiuytre1')
			// console.info(`xx:`, xx)
		},
		methods: {
			// 版本更新
			async getVersionEv() {
				let resp = await indexApi.getVersion({ t: new Date().getTime() })
				setTimeout(() => {
					uni.webView.postMessage({
						data: {
							message: 'update_version',
							data: resp
						}
					})
				}, 1000)
			},
			async getLoginImg() {
				try {
					if (this.isDisabled) {
						this.$refs.uToast.show({
							title: '请稍后再试',
							type: 'warning ',
							icon: true
						})
						return
					}
					const resp = await loginApi.getImage()
					const { data } = resp
					this.codeKey = data.data
					this.loginImg = 'data:image/*;base64,' + data.data.img
					this.isDisabled = true // 禁用按钮
					setTimeout(() => {
						this.isDisabled = false // 恢复按钮可点击
					}, 3000) // 设置等待时间为5秒（5000毫秒）
				} catch (error) {
					uni.showToast({
						title: '获取验证码失败',
						icon: 'error'
					})
					this.loginImg = null
					this.isDisabled = false
					console.error(error)
				}
			},
			async init() {
				const codeKey = await loginApi.getCodeKey()
				console.info(`codeKey:`, codeKey)
				this.codeKey = codeKey.data
				this.loginImg = 'data:image/*;base64,' + codeKey.data.img
			},
			async submit() {
				if (!navigator.onLine) {
					uni.showToast({
						icon: 'error',
						title: '网络已断开'
					})
					return
				}

				if (this.imgCode == '') {
					return this.$refs.uToast.show({
						title: '请输入图片验证码',
						type: 'warning ',
						icon: true
					})
				}
				if (this.imgCode.toLowerCase() != this.codeKey.code.toLowerCase()) {
					return this.$refs.uToast.show({
						title: '验证码错误',
						type: 'warning ',
						icon: true
					})
				}

				if (this.userName == '') {
					return this.$refs.uToast.show({
						title: '请输入账号',
						type: 'warning ',
						icon: true
					})
				}
				if (this.password == '') {
					return this.$refs.uToast.show({
						title: '请输入密码',
						type: 'warning ',
						icon: true
					})
				}
				// function containsSpecialChar(password) {
				// 	const specialChars = /[!@#$%^&*(),.?":{}|<>]/ // 定义特殊字符的正则表达式
				// 	return specialChars.test(password)
				// }
				// if (containsSpecialChar(this.password)) {
				// 	return this.$refs.uToast.show({
				// 		title: '密码包含特殊字符，无法登录',
				// 		type: 'warning ',
				// 		icon: true
				// 	})
				// }

				try {
					uni.showLoading({
						title: '正在登录'
					})
					const sm4 = new SM4Util()
					console.info(`sm4:`, sm4)
					let psss = sm4.encryptCustom_CBC(this.password, '0bcefb5f5e7b26c2', 'b898a41422ab319c')
					console.info(`psss:`, psss)
					const password = psss.toString()
					const { data } = await loginApi
						.getToken({
							username: this.userName + ':e3cc3a226021fdc238bb32550647d767',
							// password: this.password,
							password: `${password}`,
							code: this.codeKey.code,
							grant_type: 'password',
							scope: 'server',
							realKey: this.codeKey.realKey,
							grant_type: 'password',
							password_type: 'SM4'
							// Authorization: 'Basic d3BkOndwZA=='
						})
						.catch((error) => {
							console.info(`error:`, error.response)
							throw error.response
						})
					if (data) {
						uni.setStorageSync('access_token', data.access_token)
						uni.setStorageSync('userInfo', data)
					}

					// 获取地区树
					let getDeptTreeData = await loginApi.getDeptTree({ Authorization: data.access_token })
					getDeptTreeData = this.codeFatherByTree(getDeptTreeData.data.data)
					uni.setStorageSync('getDeptTreeData', getDeptTreeData)

					// 获取用户信息
					let getUserInfoData = await loginApi.getUserInfo({ Authorization: data.access_token })
					getUserInfoData = getUserInfoData.data.data
					let parentItem = this.findItemById(getDeptTreeData[0], getUserInfoData.dept.id)
					console.info(`parentItem:`, parentItem)

					let tNodeLevel = this.getNodeLevelById([getDeptTreeData[0]], getUserInfoData.dept.id)
					// 0市 1县 2乡镇街道
					let obj = {
						0: 'CITY',
						1: 'COUNTY',
						2: 'TOWNSHIP'
					}
					getUserInfoData.dept.areaLevel = tNodeLevel
					getUserInfoData.dept.areaType = obj[tNodeLevel]
					getUserInfoData.dept.parentCode = parentItem.parentCode || ''
					getUserInfoData.nickName = getUserInfoData.nickName || getUserInfoData.userName
					uni.setStorageSync('getUserInfoData', getUserInfoData)

					this.$hideLoading()

					uni.showToast({
						title: '登录成功',
						success: () => {
							// 记住密码
							if (this.isReMima) {
								this.$setItem('rePass', {
									userName: this.userName,
									password: this.password
								})
							} else {
								this.$setItem('rePass', {
									userName: '',
									password: ''
								})
							}

							setTimeout(() => {
								// uni.$emit('updateUserInfo')
								uni.redirectTo({ url: this.toUrl })
							}, 1000)
						}
					})

					Vue.prototype.UserInfoData = getUserInfoData
					Vue.prototype.DeptTreeData = getDeptTreeData
					Vue.prototype.UserInfo = data

					// 管理员角色 权限列表
					let magList = await userMagApi.getUserPower(getUserInfoData.id, {
						projectId: 'e3cc3a226021fdc238bb32550647d767'
					})
					const magListData = magList.data
					const { extend, result } = magListData
					const rolesList = extend.filter((item) => result.roles.includes(item.id))
					this.$setItem('magList', extend)
					this.$setItem('rolesList', rolesList)
					this.setUUidAndUserId(getUserInfoData, rolesList)
				} catch (error) {
					this.$hideLoading()
					console.error(error)
					if (error.status) {
						if (error.status == 426) {
							uni.showToast({
								title: '账号或密码错误',
								icon: 'error'
							})
						}
						if (error.status == 500 && error.data.data.indexOf('invalid') > -1) {
							uni.showToast({
								title: '登录超过次数，已锁定',
								icon: 'error'
							})
						}

						return
					}
					uni.showToast({
						title: '登录失败，请联系管理员',
						icon: 'error'
					})
				}
			},
			// access_token获取用户信息 并且设置
			async getAndSetSystemUserInfo(access_token) {
				// 获取地区树
				let getDeptTreeData = await loginApi.getDeptTree({ Authorization: access_token })
				getDeptTreeData = this.codeFatherByTree(getDeptTreeData.data.data)
				uni.setStorageSync('getDeptTreeData', getDeptTreeData)

				// 获取用户信息
				let getUserInfoData = await loginApi.getUserInfo({ Authorization: access_token })
				getUserInfoData = getUserInfoData.data.data
				let parentItem = this.findItemById(getDeptTreeData[0], getUserInfoData.dept.id)
				console.info(`parentItem:`, parentItem)

				let tNodeLevel = this.getNodeLevelById([getDeptTreeData[0]], getUserInfoData.dept.id)
				// 0市 1县 2乡镇街道
				let obj = {
					0: 'CITY',
					1: 'COUNTY',
					2: 'TOWNSHIP'
				}
				getUserInfoData.dept.areaLevel = tNodeLevel
				getUserInfoData.dept.areaType = obj[tNodeLevel]
				getUserInfoData.dept.parentCode = parentItem.parentCode || ''
				getUserInfoData.nickName = getUserInfoData.nickName || getUserInfoData.userName
				uni.setStorageSync('getUserInfoData', getUserInfoData)
				Vue.prototype.UserInfoData = getUserInfoData
				Vue.prototype.DeptTreeData = getDeptTreeData
				// Vue.prototype.UserInfo = data
			},
			codeFatherByTree(tree, parentCode = null) {
				tree.map((el) => {
					el.parentCode = parentCode
					if (el.children && el.children.length > 0) {
						el.children = this.codeFatherByTree(el.children, el.code)
					}
					return el
				})
				return tree
			},
			findItemById(tree, id, index = 0) {
				if (tree.id === id) {
					return tree
				} else if (tree.children) {
					for (let i = 0; i < tree.children.length; i++) {
						let result = this.findItemById(tree.children[i], id)
						if (result) {
							return result
						}
					}
				}
				return null
			},
			getNodeLevelById(nodeList, id) {
				console.info(`id:`, id)
				var level = 0

				function findNode(list, parentId, depth) {
					for (var i = 0; i < list.length; i++) {
						if (list[i].id === parentId) {
							level = depth
							break
						} else if (list[i].children) {
							findNode(list[i].children, parentId, depth + 1)
						}
					}
				}

				findNode(nodeList, id, 0)
				return level
			},

			actionClcik(index) {
				if (index == 0) {
					uni.webView.postMessage({
						data: {
							message: 'loginOut'
						}
					})
				}
				if (index == 1) {
					uni.clearStorageSync()
					uni.showToast({
						title: '清除缓存成功'
					})
				}
				console.info(`indexinde:`, index)
			},

			yehuoLogin() {
				const resp = userMagApi.yhlogin({
					account: 'admin',
					password: 'admin123'
				})
				console.info(`resp:`, resp)
			},
			/**
			 * 开始绑定设备id和用户id
			 */
			async setUUidAndUserId(getUserInfoData, rolesList = []) {
				console.info(` getUserInfoData.id:`, getUserInfoData.id)
				console.info(` this.$cid:`, this.$cid)
				let nameArr = rolesList.map((el) => el.name)
				let data = {
					// id: 0,
					userId: getUserInfoData.id,
					uuid: this.$cid,
					userName: getUserInfoData.nickName,
					areaCode: getUserInfoData.dept.code,
					areaName: getUserInfoData.dept.name,
					userRole: nameArr.join('、')
				}
				console.info(`data:`, data)
				let resp = await loginApi.addOrEdit(data)
				console.info(`resp:`, resp)
			},
			checkboxChange(value) {
				this.$setItem('isReMima', value.value)
				console.info(`value:`, value)
			}
			// isReMima(){
			// 	console.info(`isReMima:`,isReMima)
			// }
		}
	}
</script>
<style lang="less" scoped>
	.login-page {
		position: relative;
		width: 750rpx;
		// overflow: hidden;
		.login-box {
			position: absolute;
			width: 660rpx;
			// height: 375rpx;
			left: 45rpx;
			top: 714rpx;
			background: #ffffff;
			box-shadow: 0rpx 4rpx 10rpx rgba(0, 0, 0, 0.25);
			border-radius: 10rpx;
			padding: 40rpx 80rpx;
			.line-box {
				border-bottom: 1rpx solid rgba(0, 0, 0, 0.075);
			}
			.login-btn {
				// width: 226rpx;
				// height: 69rpx;
				padding: 15rpx 35rpx;
				letter-spacing: 15rpx;
				text-indent: 15rpx;
				background: #41a4ff;
				color: #ffffff;
				border-radius: 10rpx;
				box-shadow: 2rpx 2rpx 6rpx rgba(0, 0, 0, 0.11);
			}

			.checkboxMima {
				position: absolute;
				left: 7rpx;
				bottom: 7rpx;
			}
		}
		.posSet {
			position: absolute;
			bottom: 20rpx;
			right: 20rpx;
		}
		.reload-btn {
			padding: 15rpx 35rpx;
			letter-spacing: 15rpx;
			text-indent: 15rpx;
			background: #41a4ff;
			color: #ffffff;
			border-radius: 10rpx;
			box-shadow: 2rpx 2rpx 6rpx rgba(0, 0, 0, 0.11);
		}
	}
</style>
